<?php

// 编辑角色
// PUT admin.rbac.role.edit

namespace app\api\resource\admin\rbac\role;
use think\Db;
use app\common\validate\Role as RoleValidate;

class Edit
{
    // 方法
    public $_method = ['PUT','OPTIONS'];
    // 前置
    public $_pre    = ['superManager'];
    // 描述
    public $_description = '编辑角色';
    // 参数
    public $_param  = [
        'id'          => '主键',
        'name'        => '角色名',
        'description' => '描述',
    ];

    public function run(&$request)
    {
        $params = $request->param();
        
        $validate = new RoleValidate;
        if ( !$validate->scene('edit')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $ret = Db::name('rbac_role')->where('name',$params['name'])->where('id','neq',$params['id'])->find();
        if ( !is_null($ret) ) return [400,'角色名已存在'];

        $data['name']        = $params['name'];
        $data['description'] = $params['description'];
        $num = Db::name('rbac_role')->where('id',$params['id'])->update($data);

        return ($num >= 0) ? [201,'编辑成功'] : 500;
    }
}